/* 
 Better Del.icio.us Bookmarklet
 	2/2008 by Ben Dalton <bendalton -at- gmail>                                     
    
	If I have made any omissions, please contact me and I will update this list.

 	Special thanks to the parties listed below:
 	Portions taken directly from and inspired by XRAY <http://www.westciv.com/xray/>
	Some portions (c) 2007 Western Civilisation pty. ltd. http://westciv.com/xray/
	Some portions adapted from Quirksmode http://quirksmode.org and
	a tutorial aby Patrick Hunlock http://www.hunlock.com/
	The BOOKMARKPANEL style inspired by the Shiira Project's HMBlkAppKit http://shiira.jp/hmblkappkit/en.html
	Concept inspired by Left Logic's Microformats Bookmarklet http://leftlogic.com/lounge/articles/microformats_bookmarklet/
	itself from an original concept by Jon Hicks http://www.hicksdesign.co.uk/

*/

// Handle Drag And Drop
//drag and drop support adapted fom http://www.hunlock.com/blogs/Javascript_Drag_and_Drop
var BetterDeliciousBookmarklet = function()  {

	var savedTarget=null;   // The target layer (effectively vidPane)
	var orgCursor=null;     // The original mouse style so we can restore it
	var dragOK=false;       // True if we're allowed to move the element under mouse
	var dragXoffset=0;      // How much we've moved the element on the horozontal
	var dragYoffset=0;      // How much we've moved the element on the verticle
	var didDrag=false;		//set to true when we do a drag

	function moveHandler(e){
	   	if (e == null) { e = window.event } 
	   	if (e.button<=1&&dragOK){
	      	savedTarget.style.left=e.clientX-dragXoffset+'px';
	      	savedTarget.style.top=e.clientY-dragYoffset+'px';
			return false;
	   	}
	}

	function cleanup(e) {
	   	document.onmousemove=null;
	   	//document.onmouseup = xRayEvent;
		savedTarget.style.cursor=orgCursor;

	   	dragOK=false; //its been dragged now
	   	didDrag=true;

	}


	// Handle UI Creation and Display

	function insertPANEL () {
		// inserts a div we use for reporting element information

		var thePanel = document.createElement('div');
		document.body.appendChild(thePanel);
		thePanel.id='BOOKMARKPANEL';
		setElementProperty(thePanel, "visibility", "visible" );

	}

	function welcomeToBOOKMARK(){
		var thePanel = document.getElementById("BOOKMARKPANEL");
		var newPANELContent	
		newPANELContent= '<div id="elementInfo" class="elementInfo">';
		newPANELContent= newPANELContent+'<span class="BOOKMARKclosebox" onMouseUp="BetterDeliciousBookmarklet.uninstallBOOKMARK();"></span>';
		newPANELContent= newPANELContent+'<p class="BOOKMARKtitlebar">Del.icio.us Quick Bookmark</p>';  

		newPANELContent= newPANELContent+'</div>';                                                 
		newPANELContent= newPANELContent+'<form method="post" action="https://api.del.icio.us/v1/posts/add" id="dForm" onSubmit="BetterDeliciousBookmarklet.submitForm();return false;">'
		newPANELContent= newPANELContent+'<input type="hidden" name="auth" value="supersecret"/>'
		newPANELContent= newPANELContent+'URL: <input id="dURL" name="url" size="50" value="'+window.location+'"/><br/>';       
		newPANELContent= newPANELContent+'Description: <input id="dDescription" name="description"/><br/>';
		newPANELContent= newPANELContent+'Tags: <input name="tags"/><br/>'; 
		newPANELContent= newPANELContent +'<div id="BOOKMARKabout">';
		newPANELContent= newPANELContent+'<p><a onMouseUp="BetterDeliciousBookmarklet.submitForm();return true;">Add Bookmark</a></p>';
		newPANELContent= newPANELContent+'</div>';
		thePanel.innerHTML=newPANELContent;
	
		placePANEL(window.innerHeight/2-thePanel.offsetHeight/2, window.innerWidth/2);
		
	}

	function placePANEL(elementTop, elementLeft){
		//place the PANEL relative to the element we are displaying information on
	
		var thePanel = document.getElementById("BOOKMARKPANEL");
		thePanel.style.visibility='visible';
	
		if (didDrag) return; //once dragged, don't position it
	                                                
		setElementProperty(thePanel, 'top', elementTop);
		setElementProperty(thePanel, 'left', elementLeft);
	}   
 
	// insert the CSS into the DOM
	function addCSS (){
			var theHead = document.getElementsByTagName('head');
			var theCSS=document.createElement('link');
			theCSS.type = 'text/css';
			theCSS.rel='stylesheet';
			theCSS.href='http://betterdeliciousbookmarklet.googlecode.com/svn/tags/release/bdb.css';
			var theCSS = theHead[0].appendChild(theCSS);
	}


	function deleteNodeByID(nodeId) {
		//delete the node with the given id, if it exists
	
		try {
			var theNode = document.getElementById(nodeId);
			if (theNode) {
				theNode.parentNode.removeChild(theNode);
			}
		}
		catch (err) {
			//alert(err.message);
		}  
	}

	function dragHandler(e){
	      var htype='-moz-grabbing';
	      if (e == null) { e = window.event;} // htype='move';} 
	      var target = e.target != null ? e.target : e.srcElement;
	      orgCursor=target.style.cursor;

	      target=document.getElementById("BOOKMARKPANEL");
	         savedTarget=target;       
	         target.style.cursor=htype;
	         dragOK=true;
	         dragXoffset=e.clientX-target.offsetLeft;
	         dragYoffset=e.clientY-target.offsetTop;
	         document.onmousemove=moveHandler;
	         document.onmouseup=cleanup;
	         return false;    
	}

	function setElementProperty (theElement, whichStyle, theValue) {
		// set the  value for the named property for the element to the given value
		//it's returned as a string so convert to an integer if you need to use it rather than display it
		//elementCSSDeclaration=document.defaultView.getComputedStyle(theElement,"");
	    //

		if(!document.defaultView) {
			whichStyle=getIEPropertyName(whichStyle)
		}  
		if (theElement.currentStyle) {
			theElement.style.whichStyle=theValue;  
		}
		else if (window.getComputedStyle)
			theElement.style.setProperty(whichStyle, theValue, null);
	}


	function serialize(formObject)
	{
	   	var fields = formObject.elements;
	 	var queryString = formObject.action+"?";
    
		var currentField, currentValue;
		for(var i=0;i<fields.length;i++)
		{   
			currentField = fields[i].name;
		 	currentValue = fields[i].value;
			if(i > 0) queryString += "&";
			queryString += currentField+"="+URLEncode(currentValue);
		}  
	   return queryString;
	}

	//http://cass-hacks.com/articles/code/js_url_encode_decode/
	function URLEncode (clearString) {
	  var output = '';
	  var x = 0;
	  clearString = clearString.toString();
	  var regex = /(^[a-zA-Z0-9_.]*)/;
	  while (x < clearString.length) {
	    var match = regex.exec(clearString.substr(x));
	    if (match != null && match.length > 1 && match[1] != '') {
	    	output += match[1];
	      x += match[1].length;
	    } else {
	      if (clearString[x] == ' ')
	        output += '+';
	      else {
	        var charCode = clearString.charCodeAt(x);
	        var hexVal = charCode.toString(16);
	        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
	      }
	      x++;
	    }
	  }
	  return output;
	}
	
	
	
	return{

		uninstallBOOKMARK: function(){     
			//when the user closes the application, reove all the stuff, and event handlers   
			deleteNodeByID('BOOKMARKPANEL');
			},

		installBOOKMARK: function () {                                                                  
			addCSS();
			//insertCanvas();
			insertPANEL();
			//insertLabels();
			welcomeToBOOKMARK(); 
		    //setupForm();      

			var thePANEL = document.getElementById("elementInfo");
			thePANEL.onmousedown=dragHandler;
			return;
	
			document.getElementById('dDescription').focus();	
			},
	
		submitForm: function (){       
			   var dForm = document.getElementById('dForm');
			   var queryString = serialize(dForm);  
			   var fakeLoad = document.createElement('img');         
			   fakeLoad.setAttribute('id', "fakeLoad"); 
			   fakeLoad.setAttribute('src', queryString);
			   dForm.appendChild(fakeLoad);
			   uninstallBOOKMARK();
			   return false;
			}
	}
}();

BetterDeliciousBookmarklet.installBOOKMARK();
